<?php


namespace App\Game\Core;


use App\Game\Conf\SubCmd;
use App\Service\GrandMatchService;
use App\Model\User;

class Djs
{

    public static $progress_game_match = 1;
    public static $progress_game_prepare = 2;
    public static $progress_game_start = 3;
    public static $progress_game_over = 4;

    public static function createRealGame($waiters)
    {
//        Room::addUserRoomMap($account, $room_no);
//        Room::addRoomUser($account, $room_no);
//        Room::addRoomChair($account, $room_no);
//        Room::addRoomWait($room_no, $account);
//        Room::addRoomTotal($room_no);
//        //玩家准备
//        playerGamePrepare($room_no, $account);
//        $robot_conf = config('robot');
//        //添加投放机器人定时器
//        putTimerAdd(GameTimer::$ADD_DJS_ROBOT_TIMER, $room_no, $robot_conf['wait_join_timer']);
//        return $room_no;
    }

    public static function createRobotGame($account)
    {
        $room_no = self::createWaitRoom($account);

//        $players = Robot::addDjsRobots($room_no);
//
//        return ['room_no' => $room_no, 'players' => $players];

        return $room_no;
    }

    public static function joinGame($room_no, $account)
    {
        Room::addUserRoomMap($account, $room_no);
        Room::addRoomUser($account, $room_no);
        Room::addRoomChair($account, $room_no);
        $matchPlayers = [];
        $chairs = getRoomChairs($room_no);
        foreach ($chairs as $acc => $cid) {
            $uinfo = getUserInfoByAcc($acc);
            $matchPlayers[] = [
                "account" => $uinfo['account'],
                "avatar" => $uinfo['avatar'],
                "nickname" => filterNickname($uinfo['nickname']),
                "score" => (int)$uinfo['score'],
                "chair_id" => $cid,
                "prepare" => isset($prepareArr[$acc]) ? 1 : 0,
            ];
        }
        if (count($chairs) < 4) { //人数不够继续回归队列
            self::joinWaitRoom($room_no);
        }
        $playerInfo = self::getDjsPlayerData($account);
        $playerInfo['progress'] = Djs::$progress_game_prepare;
        self::updatePlayerData($account, $playerInfo);
        return $matchPlayers;
    }

    //添加等待房间队列
    public static function createWaitRoom($account)
    {
        $game_conf = config('game');
        $key = $game_conf['djs_wait_list'];
        $room_no = Room::createRoomNo();
        redis()->lPush($key, $room_no);
        //大奖赛
        Room::updateRoomData($room_no, ['game_type' => 1]);

        Room::addUserRoomMap($account, $room_no);
        Room::addRoomWait($room_no, $account);
        Room::addRoomChair($account, $room_no);
        Room::addRoomTotal($room_no);

        $robot_conf = config('robot');
        $wait_time = $robot_conf['djs_wait_join_timer'] * 1000;

        \Swoole\Timer::after((int)$wait_time, function () use ($room_no) {
            Robot::addSingleDjsRobot($room_no);
        });
        return $room_no;
    }

    //获取等待房间队列
    public static function getWaitRoom()
    {
        $game_conf = config('game');
        $key = $game_conf['djs_wait_list'];
        return redis()->rPop($key);
    }

    public static function removeWaitRoom($room_no)
    {
        $game_conf = config('game');
        $key = $game_conf['djs_wait_list'];
        redis()->lRem($key, $room_no);
    }


    //重新添加等待房间队列
    public static function joinWaitRoom($room_no, $account)
    {
        $game_conf = config('game');
        $key = $game_conf['djs_wait_list'];
        redis()->rPush($key, $room_no);
        Room::addUserRoomMap($account, $room_no);
        Room::addRoomWait($room_no, $account);
        $chair_id = Room::addRoomChair($account, $room_no);

        $robot_conf = config('robot');
        $wait_time = $robot_conf['djs_wait_join_timer'] * 1000;
        \Swoole\Timer::after((int)$wait_time, function () use ($room_no) {
            Robot::addSingleDjsRobot($room_no);
        });
        return $chair_id;
    }

    //检查积分够不够
    public static function checkScore($account)
    {
        $user_conf = config('user');
        $user_info = User::userInfo($account);
        if (($user_info['score']) > $user_conf['create_room_score']) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 匹配玩家和桌位号
     * @param $players
     * @param $room_no
     * @return mixed
     */
    public static function matchChair($players, $room_no)
    {
        $game_conf = config('game');
        $room_chair_key = sprintf($game_conf['user_room_chair'], $room_no);
        $room_chair_data = json_decode(redis()->get($room_chair_key), true);
        foreach ($players as $k => $v) {
            $players[$k]['chair_id'] = $room_chair_data[$v['account']];
        }
        return $players;
    }

    public static function addTimer($account, $wait_time)
    {
        $game_conf = config('game');
        $timerArr = json_encode(['account' => $account, 'wait_time' => $wait_time]);
        $addkey = $game_conf['djs_timer_add'];
        redis()->lPush($addkey, $timerArr);
    }

    public static function delTimer($account)
    {
        $game_conf = config('game');
        $info = self::getDjsPlayerData($account);
        $timerId = $info['timer'];
        $delkey = $game_conf['djs_timer_del'];
        redis()->lPush($delkey, $timerId);
    }

    public static function generatePlayerData($account)
    {
        $game_conf = config('game');
        $key = $game_conf['djs_player'];
        $timeArr = self::generateDjsTime();
        $data = [
            'account' => $account,
            'stage' => 1, //局数，最大10局
            'status' => 1, //大奖赛状态，0=失败 1=正常
            'turn' => 1, //轮次
            'start_time' => $timeArr['start'], //大奖赛开始时间
            'end_time' => $timeArr['end'], //大奖赛结束时间
            'alive' => 0, //复活次数,最多3次
            'get_coupons' => 0, //是否领取优惠券
            'progress' => self::$progress_game_match, //游戏进度，1.匹配中 2.准备 3.开始游戏 4.结算
        ];
//        if (redis()->ttl($key) < 1) {
//            $tomor = strtotime(date('Y-m-d',strtotime('+1 day'))) + 3600;
//            $expire = $tomor - time();
//            redis()->expire($key, $expire);
//        }
        redis()->hSet($key, (string)$account, json_encode($data));
        return $data;
    }

    public static function generateDjsTime()
    {
//        $start_time = time();
//        $end_time = $start_time + 60 * 60; //45分钟结束
        $start_time = time() - 60 * 50;
        $end_time = time() + 60 * 10; //45分钟结束
        return ['start' => $start_time, 'end' => $end_time];
    }

    public static function updatePlayerData($account, $data)
    {
//        dd('updatePlayerData', $data);
        $game_conf = config('game');
        $key = $game_conf['djs_player'];
        redis()->hSet($key, (string)$account, json_encode($data));
    }

    public static function getDjsPlayerData($account)
    {
        $game_conf = config('game');
        $key = $game_conf['djs_player'];
        if (!redis()->hExists($key, (string)$account)) {
            return [];
        }
        $res = redis()->hGet($key, (string)$account);
        return json_decode($res, true);
    }

    public static function initMatchData($room_no)
    {
        $matchPlayers = [];
        $chairs = Room::getRoomChairs($room_no);
        foreach ($chairs as $acc => $cid) {
//            dd('acc', $acc);
            $uinfo = User::userInfo($acc);
            $score = (int)$uinfo['score'];
            $statge = 1;
            $start_time = 0;
            if (!Robot::isRobot($room_no, $acc)) { //真人
                $playerInfo = self::getDjsPlayerData($acc);
//                dd('playerInfo', $playerInfo);
                $statge = $playerInfo['stage'];
                $start_time = $playerInfo['start_time'];
            } else {//机器人
                $robot = Robot::getRoomRobot($room_no, $acc);
                $score = (int)$robot;
            }
            $matchPlayers[] = [
                "account" => $uinfo['account'],
                "avatar" => $uinfo['avatar'],
                "nickname" => filterNickname($uinfo['nickname']),
                "score" => $score,
                "chair_id" => $cid,
                "prepare" => 0,
                'stage' => $statge,
                'start_time' => $start_time
            ];
        }
        //大奖赛
        Room::updateRoomData($room_no, ['game_type' => 1]);
        return $matchPlayers;
    }


    //本轮结束
    public static function roundOver($room_no, $calularData)
    {
        $data = [];
        foreach ($calularData as $v) {
            if ($v['is_robot']) {
                $data[] = $v;
                continue;
            }
            $account = $v['account'];
//            $win = $v['score'] >= 0 ? 1 : 0;
            $win = 0;
            $playerInfo = self::getDjsPlayerData($account);
            $playerInfo['progress'] = Djs::$progress_game_over;
            $playerInfo['status'] = 0;
            if ($win) {
                $playerInfo['status'] = 1;
            }
            self::updatePlayerData($account, $playerInfo);
            $round_num = $playerInfo['stage'];
            $curr_prize = [];
            if ($win) {
                // 当前奖励
                $curr_prize = GrandMatchService::getRoundPrize($round_num);
                if (empty($curr_prize)) {
                    // 下局奖励
                    $next_prize_arr = GrandMatchService::getNextStagePrize($round_num);
                    $next_prize = GrandMatchService::showPrize($next_prize_arr);
                } else {
                    $curr_prize = GrandMatchService::showPrize($curr_prize);
                }
                // 上局奖励查询
                $pre_prize_arr = GrandMatchService::getPreStagePrize($round_num);
                $pre_prize = GrandMatchService::showPrize($pre_prize_arr);
            } else {
                // 下局奖励
                $next_prize_arr = GrandMatchService::getNextStagePrize($round_num);
                $next_prize = GrandMatchService::showPrize($next_prize_arr);
                // 上局奖励查询
                $pre_prize_arr = GrandMatchService::getPreStagePrize($round_num);
                $pre_prize = GrandMatchService::showPrize($pre_prize_arr);
            }

            $over_time = 0;
            if ($playerInfo['end_time'] - time() <= 0) {
                $over_time = 1;
            }
            $v['is_win'] = $win;
            $v['stage'] = $round_num;
            $v['turn'] = $playerInfo['turn'];
            $v['status'] = $playerInfo['status'];
            $v['alive'] = $playerInfo['alive'];
            $v['start_time'] = $playerInfo['start_time'];
            $v['curr_prize'] = $curr_prize;
            $v['next_prize'] = $next_prize;
            $v['pre_prize'] = $pre_prize;
            $v['over_time'] = $over_time;

            $data[] = $v;
            //移除用户-房间的绑定关系
            Room::removeUserRoomMap($account, $room_no);
        }
        Message::broadcast($room_no, $data, SubCmd::GAME_DJS_OVER);
        //清除房间数据
        Room::cleanRoom($room_no);
    }

    public
    static function cleanDjsData()
    {
        $game_conf = config('game');
        $key = $game_conf['djs_player'];
        redis()->del($key);
        $key = $game_conf['djs_wait_list'];
        redis()->del($key);
    }

}